package com.hikealoha.hikealoha;

import com.att.m2x.client.*;

import android.location.*;
import android.os.AsyncTask;
import android.util.Log;

import java.io.IOException;

public class M2XHandlerAsync extends AsyncTask<Location, Void, Void> {
    private final static String DEV_API_KEY = "d4fa4af6abd36946b857abfd8c612834";
    private final static String ANON_API_KEY = "7dd1c8c0877bd4fc71a7b0e917bb58f7";
    private final static String anonDeviceID = "a3d7c4be489c4467616bd22365ccb33d";
    private final static String deviceID = "fb373230803fc8b42c211d53c5b08284";

    protected Void doInBackground(Location... locations) {
        // Set up devices.
        M2XClient devClient = new M2XClient(DEV_API_KEY);
        M2XClient anonClient = new M2XClient(ANON_API_KEY);
        M2XDevice device = devClient.device(deviceID);
        M2XDevice anonDevice = anonClient.device(anonDeviceID);

        // Send the data.
        for (Location location : locations) {
            if (isCancelled()) break;

            double lat = location.getLatitude();
            double lon = location.getLongitude();

            try {
                // TODO: Check to make sure the user is okay with us uploading emergency-services data.
                device.stream("GPS-LAT").updateValue("{\"value\":" + lat + "}");
                device.stream("GPS-LONG").updateValue("{\"value\":" + lon + "}");
                // TODO: Check to make sure the user is okay with us uploading anonymized data.
                anonDevice.stream("GPS-LAT").updateValue("{\"value\":" + lat + "}");
                anonDevice.stream("GPS-LONG").updateValue("{\"value\":" + lon + "}");
            } catch (IOException e) {
                System.err.println("Error when uploading GPS data to server: " + e.getMessage());
                Log.i("IOEx", "Error when uploading GPS data to server: " + e.getMessage());
                return null;
            }
        }
        return null;
    }

    protected void onProgressUpdate(Void... voids) {
    }
}